package clustersync

import("fmt";
	   "./clustersolution");

type SignalChan struct {
	Best *clustersolution.ClusterSolution;
}

func server(service chan *clustersolution.AccelerationRequest,
			signal chan *SignalChan) {
	var bestSeen clustersolution.ClusterSolution;
	init := <-service;
	bestSeen.DeepCopy(init.Mine);
	fmt.Println("Initial Fitness: ",bestSeen.Fitness);	
	init.Result <-&bestSeen;
	for {
		select {
		case req := <-service:
			if req.Mine.Fitness < bestSeen.Fitness {
				fmt.Println("Fitness: ",req.Mine.Fitness);
				bestSeen.DeepCopy(req.Mine);
			}
			req.Result <-&bestSeen;
		case retval := <-signal:
			retval.Best = &bestSeen;
			signal <-retval;
			return;
		}
	}
}

func StartServer() (chan *clustersolution.AccelerationRequest, chan *SignalChan) {
	reqChan := make(chan *clustersolution.AccelerationRequest);
	sigChan := make(chan *SignalChan);
	go server(reqChan, sigChan);
	return reqChan, sigChan;
}
